package com.fer.t1.client;

import com.fer.t1.client.pages.multiStep.MultiStepHistoryManager;
import com.google.gwt.user.client.History;


public class PageManager {

	/**
	 * Dispatches a new history event with the following form<br>
	 * <br>
	 * <b>#url/paramsValue[0]=paramsValue[1]&paramsValue[2]=paramsValue[3]&...</b>
	 * @param url the base url
	 * @param paramsValue a paramValue list. In order for this method not to throw an Exception there must
	 * be an even number of paramsValue. The first must be the paramName, the second must be its value 
	 */
	public static void goTo(String url, String... paramsValue )
	{
		
		String history = getURL(url, paramsValue);
		History.newItem(history);
		
	}
	
	public static void goTo(String url, int step, String... paramsValue )
	{
		String history = getURL(url,step,paramsValue);
		System.out.println(history);
		History.newItem(history);
	}
	
	public static String getURL(String url, int step, String... paramsValue) {
		String history = getURL(url, paramsValue);
		
		if (paramsValue.length == 0)
		{
			history += HistoryManager.Constants.QUERY + MultiStepHistoryManager.STEP + HistoryManager.Constants.PARAM_EQUAL + step;
		}
		else
		{
			history += HistoryManager.Constants.PARAM_AND + MultiStepHistoryManager.STEP + HistoryManager.Constants.PARAM_EQUAL + step;
		}
		return history;
	}

	public static String getURL(String url, String... paramsValue )
	{
		if (paramsValue.length%2!=0)
		{
			throw new IllegalArgumentException("paramsValue size is incorrect");
		}
		
		String params = "";
		for (int i = 0; i < paramsValue.length; i+=2) {
			
			String param = paramsValue[i];
			String value = paramsValue[i+1];
			params += param + HistoryManager.Constants.PARAM_EQUAL + value;
			
			if (i+2 < paramsValue.length)
			{
				params += HistoryManager.Constants.PARAM_AND;
			}
		}
		
		String history = "";
		
		if (paramsValue.length==0)
		{
			history = url;
		}
		else
		{
			history = url + HistoryManager.Constants.QUERY + params;
		}
		return history;
	}
	
}
